import userApi from '../../../js/api.js';

document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('register-form');
    const usernameInput = document.getElementById('username');
    const emailInput = document.getElementById('email');
    const passwordInput = document.getElementById('password');
    const confirmPasswordInput = document.getElementById('confirm-password');

    // 添加表单验证
    function validateForm() {
        let isValid = true;

        // 验证用户名
        if (!usernameInput.value.trim()) {
            showError(usernameInput, '用户名不能为空');
            isValid = false;
        } else if (usernameInput.value.length < 3) {
            showError(usernameInput, '用户名至少需要3个字符');
            isValid = false;
        } else {
            clearError(usernameInput);
        }

        // 验证邮箱
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailInput.value.trim()) {
            showError(emailInput, '邮箱不能为空');
            isValid = false;
        } else if (!emailRegex.test(emailInput.value)) {
            showError(emailInput, '请输入有效的邮箱地址');
            isValid = false;
        } else {
            clearError(emailInput);
        }

        // 验证密码
        if (!passwordInput.value) {
            showError(passwordInput, '密码不能为空');
            isValid = false;
        } else if (passwordInput.value.length < 6) {
            showError(passwordInput, '密码至少需要6个字符');
            isValid = false;
        } else {
            clearError(passwordInput);
        }

        // 验证确认密码
        if (!confirmPasswordInput.value) {
            showError(confirmPasswordInput, '请确认密码');
            isValid = false;
        } else if (confirmPasswordInput.value !== passwordInput.value) {
            showError(confirmPasswordInput, '两次输入的密码不一致');
            isValid = false;
        } else {
            clearError(confirmPasswordInput);
        }

        return isValid;
    }

    // 显示错误信息
    function showError(input, message) {
        const formGroup = input.parentElement;
        formGroup.classList.add('error');
        
        let errorDiv = formGroup.querySelector('.error-message');
        if (!errorDiv) {
            errorDiv = document.createElement('div');
            errorDiv.className = 'error-message';
            formGroup.appendChild(errorDiv);
        }
        errorDiv.textContent = message;
    }

    // 清除错误信息
    function clearError(input) {
        const formGroup = input.parentElement;
        formGroup.classList.remove('error');
        const errorDiv = formGroup.querySelector('.error-message');
        if (errorDiv) {
            errorDiv.remove();
        }
    }

    // 处理表单提交
    form.addEventListener('submit', async function(e) {
        e.preventDefault();

        if (!validateForm()) {
            return;
        }

        try {
            const userData = {
                username: usernameInput.value.trim(),
                email: emailInput.value.trim(),
                password: passwordInput.value
            };

            const response = await userApi.register(userData);
            
            if (response.token) {
                // 注册成功，保存token并跳转
                localStorage.setItem('token', response.token);
                window.location.href = '../../../html/home.html';
            } else {
                // 注册失败，显示错误信息
                alert(response.message || '注册失败，请稍后重试');
            }
        } catch (error) {
            console.error('Registration error:', error);
            alert('注册失败，请稍后重试');
        }
    });

    // 实时验证
    usernameInput.addEventListener('blur', () => validateField(usernameInput));
    emailInput.addEventListener('blur', () => validateField(emailInput));
    passwordInput.addEventListener('blur', () => validateField(passwordInput));
    confirmPasswordInput.addEventListener('blur', () => validateField(confirmPasswordInput));

    function validateField(input) {
        const dummyEvent = { preventDefault: () => {} };
        validateForm(dummyEvent);
    }
});
